package com.android.common.utils.media;

import android.content.Context;
import android.net.Uri;
import android.util.Log;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import com.android.common.R;
import com.android.common.base.rv.BaseRvAdapter;
import com.luck.picture.lib.animators.AnimationType;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.FileSizeUnit;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.config.SelectLimitType;
import com.luck.picture.lib.config.SelectModeConfig;
import com.luck.picture.lib.config.SelectorConfig;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.luck.picture.lib.interfaces.OnSelectLimitTipsListener;
import com.luck.picture.lib.style.PictureSelectorStyle;
import com.luck.picture.lib.style.PictureWindowAnimationStyle;
import com.luck.picture.lib.utils.DateUtils;
import com.luck.picture.lib.utils.ToastUtils;
import java.io.File;
import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;
import top.zibin.luban.CompressionPredicate;
import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;
import top.zibin.luban.OnRenameListener;


public class MediaSelectorUtils {

    private static final String TAG = "MediaSelector";

    public static void previewMedia(Fragment fragment,int position , BaseRvAdapter<LocalMedia> adapter) {
        PictureSelectorStyle selectorStyle = new PictureSelectorStyle();;
        PictureWindowAnimationStyle defaultAnimationStyle = new PictureWindowAnimationStyle();
        defaultAnimationStyle.setActivityEnterAnimation(R.anim.ps_anim_enter);
        defaultAnimationStyle.setActivityExitAnimation(R.anim.ps_anim_exit);
        selectorStyle.setWindowAnimationStyle(defaultAnimationStyle);
        // 预览图片、视频、音频
        PictureSelector.create(fragment)
                .openPreview()
                .setImageEngine(GlideEngine.createGlideEngine())
                .setSelectorUIStyle(selectorStyle)
                .startActivityPreview(position, false, (ArrayList<LocalMedia>) adapter.getData());
    }

    /**
     *
     * @param chooseMode 图片、视频等
     * @param maxSelectNum 最大可选多媒体
     * @param maxSelectVideoNum 最大可选视频
     * @param maxFileSize  最大可选文件大小
     * @param onResultCallbackListener 选择文件后的回调
     */
    public static void selectMedia(Context context, int chooseMode, int maxSelectNum, int maxSelectVideoNum, long maxFileSize
        , List<LocalMedia> selectedList,OnResultCallbackListener<LocalMedia> onResultCallbackListener){
        PictureSelectorStyle selectorStyle = new PictureSelectorStyle();
        PictureWindowAnimationStyle defaultAnimationStyle = new PictureWindowAnimationStyle();
        defaultAnimationStyle.setActivityEnterAnimation(R.anim.ps_anim_enter);
        defaultAnimationStyle.setActivityExitAnimation(R.anim.ps_anim_exit);
        selectorStyle.setWindowAnimationStyle(defaultAnimationStyle);
        PictureSelector.create(context)
                .openGallery(chooseMode)
                .setSelectorUIStyle(selectorStyle)
                .setImageEngine(GlideEngine.createGlideEngine())
                .setSelectLimitTipsListener(new OnSelectLimitTipsListenerImpl())
                .isPageSyncAlbumCount(true)
                .setQueryFilterListener(media -> false)
                //.setExtendLoaderEngine(getExtendLoaderEngine())
                .setSelectionMode(SelectModeConfig.MULTIPLE)
                .isDisplayTimeAxis(true)
                .isPageStrategy(true)
                .isOriginalControl(true)
                .isDisplayCamera(true)
                .setSkipCropMimeType(getNotSupportCrop())
                .isFastSlidingSelect(true)
                //.setOutputCameraImageFileName("luck.jpeg")
                //.setOutputCameraVideoFileName("luck.mp4")
                .isWithSelectVideoImage(true)
                .isPreviewFullScreenMode(true)
                .isVideoPauseResumePlay(true)
                .isPreviewZoomEffect(true)
                .isPreviewImage(true)
                .isPreviewVideo(true)
                .isPreviewAudio(true)
                //.setQueryOnlyMimeType(PictureMimeType.ofGIF())
                .isMaxSelectEnabledMask(true)
                .isDirectReturnSingle(true)
                .setMaxSelectNum(maxSelectNum)
                .setMaxVideoSelectNum(maxSelectVideoNum)
                .setSelectMaxFileSize(maxFileSize* FileSizeUnit.MB)
                .setFilterVideoMaxSecond(30)
                .setRecyclerAnimationMode(AnimationType.DEFAULT_ANIMATION)
                .isGif(true)
                .setCompressEngine(new ImageFileCompressEngine())
                .setSelectedData(selectedList)
                .forResult(onResultCallbackListener);
    }

    /**
     *
     * @param context
     * @param chooseMode 图片、视频等
     * @param maxSelectNum 最大可选多媒体
     * @param maxSelectVideoNum 最大可选视频
     * @param maxFileSize  最大可选文件大小
     * @param adapter
     */
    public static void selectMedia(Context context, int chooseMode, int maxSelectNum,int maxSelectVideoNum, long maxFileSize, BaseRvAdapter<LocalMedia> adapter){
        selectMedia(context,chooseMode,maxSelectNum,maxSelectVideoNum,maxFileSize,adapter.getData(),new MediaSelectorResultCallback(adapter));
    }

    private static String[] getNotSupportCrop() {
        return new String[]{PictureMimeType.ofGIF(), PictureMimeType.ofWEBP()};
    }



    public static class MediaSelectorResultCallback  implements OnResultCallbackListener<LocalMedia> {
        private WeakReference<BaseRvAdapter> mAdapterWeakReference;
        private final static String TAG = "MyResultCallback";

        public MediaSelectorResultCallback(BaseRvAdapter adapter) {
            super();
            this.mAdapterWeakReference = new WeakReference<>(adapter);
        }

        @Override
        public void onResult(ArrayList<LocalMedia> result) {
            if (mAdapterWeakReference.get() != null) {
                mAdapterWeakReference.get().setDataAndNotify(result);
            }
        }

        @Override
        public void onCancel() {
            Log.i(TAG, "PictureSelector Cancel");
        }
    }

    /**
     * 拦截自定义提示
     */
    private static class OnSelectLimitTipsListenerImpl implements OnSelectLimitTipsListener {

        @Override
        public boolean onSelectLimitTips(Context context, @Nullable LocalMedia media, SelectorConfig config, int limitType) {
            if (limitType == SelectLimitType.SELECT_MIN_SELECT_LIMIT) {
                ToastUtils.showToast(context, "图片最少不能低于" + config.minSelectNum + "张");
                return true;
            } else if (limitType == SelectLimitType.SELECT_MIN_VIDEO_SELECT_LIMIT) {
                ToastUtils.showToast(context, "视频最少不能低于" + config.minVideoSelectNum + "个");
                return true;
            } else if (limitType == SelectLimitType.SELECT_MIN_AUDIO_SELECT_LIMIT) {
                ToastUtils.showToast(context, "音频最少不能低于" + config.minAudioSelectNum + "个");
                return true;
            }
            return false;
        }
    }

    /**
     * 自定义压缩
     */
    private static class ImageFileCompressEngine implements CompressFileEngine {

        @Override
        public void onStartCompress(Context context, ArrayList<Uri> source, OnKeyValueResultCallbackListener call) {
            Luban.with(context).load(source).ignoreBy(100).setRenameListener(new OnRenameListener() {
                @Override
                public String rename(String filePath) {
                    int indexOf = filePath.lastIndexOf(".");
                    String postfix = indexOf != -1 ? filePath.substring(indexOf) : ".jpg";
                    return DateUtils.getCreateFileName("CMP_") + postfix;
                }
            }).filter(new CompressionPredicate() {
                @Override
                public boolean apply(String path) {
                    if (PictureMimeType.isUrlHasImage(path) && !PictureMimeType.isHasHttp(path)) {
                        return true;
                    }
                    return !PictureMimeType.isUrlHasGif(path);
                }
            }).setCompressListener(new OnNewCompressListener() {
                @Override
                public void onStart() {

                }

                @Override
                public void onSuccess(String source, File compressFile) {
                    if (call != null) {
                        call.onCallback(source, compressFile.getAbsolutePath());
                    }
                }

                @Override
                public void onError(String source, Throwable e) {
                    if (call != null) {
                        call.onCallback(source, null);
                    }
                }
            }).launch();
        }
    }
}
